package com.aspire.android.heliar;


import com.aspire.android.heliar.activities.PubListActivity;
import com.aspire.android.heliar.pub.PubManager;
import com.aspire.android.heliar.utils.ContextFactory;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.TextView;

public class Heliar extends Activity {

	public static final String LOG_TAG = "Heliar-Log";

	public static final String KEY_STARTUP_STEP = "step";

	public static final int STARTUP_LOAD_LOCAL_DATA = 0;
	public static final int STARTUP_CHECK_RAW_DATA = 1;
	public static final int STARTUP_GENERATE_PUB_LIST = 2;
	public static final int STARTUP_COMPLETE = 3;

	Handler progressHandler = new Handler() {
		public void handleMessage(Message message) {

			TextView textView = (TextView) findViewById(R.id.tips);
			Bundle b = message.getData();
			switch (b.getInt(KEY_STARTUP_STEP)) {
			case STARTUP_LOAD_LOCAL_DATA:
				textView.setText(R.string.heliar_startup_step_tips_load_local_data);
				break;
			case STARTUP_CHECK_RAW_DATA:
				textView.setText(R.string.heliar_startup_step_tips_check_mms_data);
				break;
			case STARTUP_GENERATE_PUB_LIST:
				textView.setText(R.string.heliar_startup_step_tips_generate_pub_list);
				break;
			case STARTUP_COMPLETE:
				// Request Pub List Activity
				Intent intent = new Intent(ContextFactory.getInstance(),
						PubListActivity.class);
				startActivityForResult(intent, 0);
				finish();
				break;
			}
		}
	};

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		init();

		setContentView(R.layout.pre_startup);
		Thread background = new Thread(new Runnable() {
			public void run() {
				Message message = progressHandler.obtainMessage();
				Bundle b = new Bundle();
				b.putInt(KEY_STARTUP_STEP, STARTUP_LOAD_LOCAL_DATA);
				message.setData(b);
				progressHandler.sendMessage(message);
				// Load Local Pub Data
				PubManager.getInstance().loadLocalStorePubs();

				message = progressHandler.obtainMessage();
				b = new Bundle();
				b.putInt(KEY_STARTUP_STEP, STARTUP_CHECK_RAW_DATA);
				message.setData(b);
				progressHandler.sendMessage(message);
				// Check Raw data
				PubManager.getInstance().syncRawDataToPub();

				message = progressHandler.obtainMessage();
				b = new Bundle();
				b.putInt(KEY_STARTUP_STEP, STARTUP_GENERATE_PUB_LIST);
				message.setData(b);
				progressHandler.sendMessage(message);
				// generate pub list
				PubManager.getInstance();

				message = progressHandler.obtainMessage();
				b = new Bundle();
				b.putInt(KEY_STARTUP_STEP, STARTUP_COMPLETE);
				message.setData(b);
				progressHandler.sendMessage(message);

			}
		});

		background.start();
	}

	public void init() {
		ContextFactory.init(this);
	}
}